package thread.lock;

/** @Package Thread.lock @Author shimmer @Date 2020/5/14 10:42 @TODO 测试死锁 */

// 死锁：多个线程锁着对方需要的线程，形成僵持

public class DeadLock {
  public static void main(String[] args) {
    MakeUp m1 = new MakeUp(0, "灰姑凉");
    MakeUp m2 = new MakeUp(1, "白雪公主");

    m1.start();
    m2.start();
  }
}

//口红
class Lipstick {}

// 镜子
class Mirror {}

// 化妆
class MakeUp extends Thread {
  // 只有一支口红和一面镜子，用static保证只有一份
  static final Lipstick lipstick = new Lipstick();
  static final Mirror mirror = new Mirror();
  // 选择和名字
  int choice;
  String name;

  MakeUp(int choice, String name) {
    this.choice = choice;
    this.name = name;
  }

  @Override
  public void run() {
    try {
      makeup();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  // 抢东西
  private void makeup() throws InterruptedException {
    if (choice == 0) {
      // 获得口红的锁
      synchronized (lipstick) {
        System.out.println(this.name + "获得口红");
        Thread.sleep(1000);
        // 想要镜子
        //        synchronized (mirror) {
        //          System.out.println(this.name + "获得镜子");
        //        }
      }
      synchronized (mirror) {
        System.out.println(this.name + "获得镜子");
      }
    } else {
      // 获得镜子的锁
      synchronized (mirror) {
        System.out.println(this.name + "获得镜子");
        Thread.sleep(2000);
        // 想要口红
//        synchronized (lipstick) {
//          System.out.println(this.name + "获得口红");
//        }
      }
        synchronized (lipstick) {
            System.out.println(this.name + "获得口红");
        }
    }
  }
}
